import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'image_editor_page.dart';

class ImgDemo extends StatefulWidget {
  const ImgDemo({super.key});

  @override
  State<StatefulWidget> createState() {
    return _ImgDemoState();
  }
}

class _ImgDemoState extends State<ImgDemo> {
  File? _selectedImage;

  Future<void> _pickImage() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      setState(() {
        _selectedImage = File(pickedFile.path);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '美图工具',
          style: TextStyle(
            fontSize: 20,
            color: const Color.fromARGB(255, 0, 0, 0),
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (_selectedImage == null)
              _buildImagePicker()
            else
              Column(
                children: [
                  // 预览图片组件
                  _buildImagePreview(),
                  // 占位区
                  SizedBox(height: 16),
                  _buildFunctionButton(),
                ],
              ),
          ],
        ),
      ),
    );
  }

  // 选择图片组件
  Widget _buildImagePicker() {
    return ElevatedButton(onPressed: _pickImage, child: Text('选择图片'));
  }

  // 预览图片组件
  Widget _buildImagePreview() {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 500,
      decoration: BoxDecoration(
        color: Colors.black, // 添加背景色以便于区分预览区域
        border: Border.all(color: Colors.grey[300]!), // 添加边框
      ),
      child: Image.file(
        _selectedImage!,
        alignment: Alignment.center,
        fit: BoxFit.contain, // 使用contain确保图片完整显示
      ),
    );
  }

  // 功能按钮组件
  Widget _buildFunctionButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        ElevatedButton(
          onPressed: _pickImage,
          child: Text('重新选择', style: TextStyle(color: Colors.black38)),
        ),
        ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder:
                    (context) => ImageEditorPage(imageFile: _selectedImage!),
              ),
            );
          },
          style: ElevatedButton.styleFrom(backgroundColor: Colors.blue[500]),
          child: Text(
            '开始编辑',
            style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          ),
        ),
      ],
    );
  }
}
